package com.PublicChest.plugin;

import com.PublicChest.plugin.command.PublicChestCommand;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.inventory.InventoryCloseEvent;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import org.bukkit.plugin.java.JavaPlugin;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;

public class PublicChest extends JavaPlugin implements Listener {
    public final File dataFolder = this.getDataFolder();
    public HashMap<String, Boolean> onVisiting = new HashMap<>();
    public final File LockFile = new File(this.dataFolder + "/lockedChests.yml");

    @Override
    public void onEnable() {
        getLogger().info("PublicChest Loaded!");
        getCommand("pchest").setExecutor(new PublicChestCommand(this));
        getCommand("lockchest").setExecutor(new PublicChestCommand(this));
        getCommand("unlockchest").setExecutor(new PublicChestCommand(this));
        Bukkit.getPluginManager().registerEvents(this, this);

        File directory = new File(String.valueOf(this.dataFolder));
        if (!directory.exists()) {
            directory.mkdir();
        }
        if (!this.LockFile.exists()) {
            try {
                this.LockFile.createNewFile();
            } catch (IOException e) {
                getLogger().info("PublicChest Create File Failed!");
            }
        }
    }

    @Override
    public void onDisable() {
        getLogger().info("PublicChest Unloaded!");
    }

    @EventHandler
    public void onClose(InventoryCloseEvent event) throws IOException {
        this.saveInv((Player) event.getPlayer(), event.getInventory());

    }

    public void saveInv(Player user, Inventory inv) throws IOException {
        if (onVisiting.get(inv.getName()) == null) {
            return;
        }
        YamlConfiguration yml = YamlConfiguration.loadConfiguration(new File(this.dataFolder + "/" + inv.getName() + ".yml"));
        yml.set("Item", null);
        ItemStack[] items = inv.getContents();
        for (int index = 0; index < items.length; index++) {
            ItemStack item = items[index];
            if (item != null && item.getType() != Material.AIR) {
                yml.set("Item." + index, item);
            }
        }
        onVisiting.remove(inv.getName());
        yml.save(new File(this.dataFolder + "/" + inv.getName() + ".yml"));
    }
}
